<template>
  <div class="countbox">
    <button class="sub" @click="handleSub">-</button>
    <input @change="handleChange" :value="value" class="inp" type="text">
    <button class="add" @click="handleAdd">+</button>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {

    }
  },
  methods: {
    handleSub () {
      if (this.value <= 1) { return }
      this.$emit('input', this.value - 1)
    },
    handleAdd () {
      this.$emit('input', this.value + 1)
    },
    handleChange (e) {
      // console.log(e.target.value)
      const sum = +e.target.value
      // 输入了不合法的文本，回退成原来的 value 值
      if (isNaN(sum) || sum < 1) {
        e.target.value = this.value
      }
      this.$emit('input', sum)
    }
  }
}
</script>

<style lang="less" scoped>
.countbox{
  width: 110px;
  display: flex;
  .sub, .add{
    width: 30px;
    height: 30px;
    border: none;
    outline: none;
    background-color: #f0f0f0;
  }
  .inp {
    width: 40px;
    height: 30px;
    margin: 0 5px;
    border: none;
    outline: none;
    text-align: center;
    background-color: #f0f0f0;
  }
}
</style>
